<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input
          v-model="query.blurry"
          clearable
          size="small"
          placeholder="输入名称或者描述搜索"
          style="width: 200px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <el-date-picker
          v-model="query.createTime"
          :default-time="['00:00:00','23:59:59']"
          type="daterange"
          range-separator=":"
          size="small"
          class="date-item"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
        <el-select
          v-model="query.enabled"
          clearable
          size="small"
          placeholder="状态"
          class="filter-item"
          style="width: 90px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in enabledOptions"
            :key="item.key"
            :label="item.display_name"
            :value="item.key"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <crudOperation show="" :permission="permission" />
    </div>
    <!--表单渲染-->
    <el-dialog
      close-on-click-modal
      destroy-on-close
      :visible.sync="crud.status.cu > 0"
      :before-close="dialogClose"
      width="99%"
      top="1vh"
    >
      <el-row style="height:535px;">
        <phuket v-if="crud.status.cu > 0" :option="phuketOption" />
      </el-row>
    </el-dialog>
    <!--表格渲染-->
    <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
      <el-table-column type="selection" width="55" />
      <el-table-column v-if="columns.visible('id')" :show-overflow-tooltip="true" prop="id" label="流程编号" />
      <el-table-column v-if="columns.visible('name')" :show-overflow-tooltip="true" prop="name" label="流程名称" />
      <el-table-column v-if="columns.visible('remark')" :show-overflow-tooltip="true" prop="remark" label="流程描述" />
      <el-table-column v-if="columns.visible('type')" :show-overflow-tooltip="true" prop="type" label="类型" />
      <el-table-column v-if="columns.visible('enabled')" label="状态" align="center" prop="enabled">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeEnabled(scope.row, scope.row.enabled)"
          />
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('createTime')" :show-overflow-tooltip="true" prop="createTime" width="140" label="创建日期">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('createBy')" align="center" prop="createBy" width="100" label="创建者" />
      <el-table-column v-if="columns.visible('lastUpdateTime')" :show-overflow-tooltip="true" prop="lastUpdateTime" width="140" label="更新日期">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.lastUpdateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="columns.visible('lastUpdateBy')" align="center" prop="lastUpdateBy" width="100" label="更新者" />
      <el-table-column
        v-permission="['admin','process:edit','process:del']"
        label="操作"
        width="125"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
  </div>
</template>

<script>
import crudProcess from '@/api/process/process'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'

// 自定义的拖拽流程控件
import Common from './phuket/Common'
import phuket from './phuket'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '流程',
  url: 'api/process',
  sort: ['id,desc', 'name,asc'],
  crudMethod: { ...crudProcess }
})
const defaultForm = { id: null, name: null, remark: null, type: null, enabled: 'false' }

export default {
  name: 'Process',
  components: { crudOperation, rrOperation, udOperation, pagination, phuket },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud()],
  // 数据字典
  dicts: ['job_status'],
  data() {
    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      // 许可
      permission: {
        add: ['admin', 'process:add'],
        edit: ['admin', 'process:edit'],
        del: ['admin', 'process:del']
      },
      // 启动状态
      enabledOptions: [
        { key: 'true', display_name: '启动' },
        { key: 'false', display_name: '停止' }
      ],
      // 选中行的数据
      selected: {},
      // phuket传入信息
      phuketOption: {
        model: 'edit', // edit、view、preview
        xml: null,
        save: () => {}
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  created() {
    Common.init(this.baseApi)
    this.crud.query.type = this.$route.name
    this.$nextTick(() => {
      this.crud.toQuery() // 查询列表
      this.crud.msg.add = '新增流程成功'
    })
  },
  mounted: function() {
    const self = this
    window.onresize = function temp() {
      self.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  methods: {
    // 关闭dialog时执行
    dialogClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          if (this.crud.status.add === CRUD.STATUS.PREPARED) {
            this.crud.status.add = CRUD.STATUS.NORMAL
          }
          if (this.crud.status.edit === CRUD.STATUS.PREPARED) {
            this.crud.status.edit = CRUD.STATUS.NORMAL
          }
        })
        .catch(_ => {})
    },
    // 新建 - 之前
    [CRUD.HOOK.beforeToAdd](form) {
      this.selected = {}
      this.phuketOption.xml = null
      this.phuketOption.save = this.phuketSave
    },
    // 编辑 - 之前
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.selected = form
      this.phuketOption.xml = form.content
      this.phuketOption.save = this.phuketSave
    },
    // 保存流程
    phuketSave(element, xml) {
      let data = {}
      if (this.selected) {
        data = this.selected
      }
      data['name'] = element.name
      data['remark'] = element.$attrs.remark
      data['content'] = xml
      data['type'] = element.$attrs.type
      if (data.id) {
        crudProcess.edit(data).then(_ => {
          this.$notify.success({
            title: '成功',
            message: '更新流程成功',
            position: 'top-right'
          })
          this.crud.status.edit = CRUD.STATUS.NORMAL
          this.crud.toQuery() // 查询列表
        }).catch(_ => {
          this.$notify.error({
            title: '失败',
            message: '更新流程失败',
            position: 'top-right'
          })
        })
      } else {
        crudProcess.add(data).then(_ => {
          this.$notify.success({
            title: '成功',
            message: '保存流程成功',
            position: 'top-right'
          })
          this.crud.status.add = CRUD.STATUS.NORMAL
          this.crud.toQuery() // 查询列表
        }).catch(_ => {
          this.$notify.error({
            title: '失败',
            message: '保存流程失败',
            position: 'top-right'
          })
        })
      }
    },
    // 改变启动状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.job_status[val] + '" ' + data.name + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudProcess.edit(data).then(res => {
          this.crud.notify(this.dict.label.job_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    }
  }
}
</script>
